package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/*
 * 文件上传接口
 * */
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private AliOSSUtils aliOSSUtils;
    //本地存储文件
   /* @PostMapping()
    //MultipartFile类型的参数可以接受上传的文件
    public Result upload(String username, Integer age, MultipartFile image) throws IOException {

        log.info("文件上传:{} {} {}", username, age, image);

        //获取原始文件名
        String filename = image.getOriginalFilename();

        //构造唯一文件名---uuid(通用唯一识别码)
        int index = filename.lastIndexOf(".");
        String extname = filename.substring(index);
        filename = filename + UUID.randomUUID().toString() +extname;

        log.info("新的文件名{}",filename);


        //将上传的文件存储到本地磁盘目录中 D:\image
        //--------
        image.transferTo(new File("D:\\image\\" + filename));

        return Result.success();
    }*/

    //MultipartFile类型的参数可以接受上传的文件
    @PostMapping
    public Result upload(MultipartFile image) throws IOException {
        log.info("文件上传,文件名:{}", image.getOriginalFilename());

        //调用阿里云oss文件工具类来进行文件上传
        String url = aliOSSUtils.upload(image);

        //响应就是把数据返回给前端
        return Result.success(url);
    }

}
